import md5 from 'md5';

const stream = weex.requireModule('stream');
const storage = weex.requireModule('storage');

const appid = '20210605000854728'; //APP ID
const salt = '432522548'; //随机数
const key = 'IUF1MYRmBmbfq1Q9Edbq'; //秘钥
const language = weex.config.language;
const languages = {'en':'en', 
                   'ja':'jp', 
                   'ko':'kor'};

 //不翻译白名单
const nos = {'nickName':'1', 
             'strategyName':'1',
             'teamName':'1',
             'projectName':'1',
             'serverName':'1',
            'serverMark':'1'}; 
export default {

  //翻译
  fy(data, back) {

    if (languages[language] == undefined) {
      back(data);
      return;
    }

    var chs = [];
    this.chaZhao(data, chs);

    var fy = {};
    this.diGui(chs, 0, fy, ()=>{
      data = this.tiHuan(data, fy);
      back(data);
    });
  },

  //抽取返回数据的中文，保存到chs
  chaZhao(data, chs) {
    
    if (data == undefined) {
      return;
    }
    
    //纯字符串，包含中文，保存。
    if (data.constructor.name == 'String') {
      try {
        data = JSON.parse(data);
        this.chaZhao(data, chs);
      } catch (e){
        var numRe = new RegExp("[\\u4E00-\\u9FFF]+","g");
        if (numRe.test(data)) {
          chs.push(data);
        }
      }
      return;
    }
    
    //数组，遍历判断
    if (data.constructor.name == 'Array') {
      for (let index = 0; index < data.length; index++) {
        var z = data[index];
        this.chaZhao(z, chs);
      }
      return;
    }

    //字典，遍历判断
    if (data.constructor.name == 'Object') {
      for (const key in data) {
        if (nos[key]) continue;
        var z = data[key];
        this.chaZhao(z, chs);
      }
      return;
    }
  },

  //查找chs里面中文对应的本地缓存英文，保存到fy
  diGui(chs, i, fy, back) {
    if (i >= chs.length) {
      back();
      return;
    }

    const ch = chs[i];
    i = i + 1;

    storage.getItem(ch, (e)=>{
      try{
        var data = JSON.parse(e.data);
        if (data[language]) {
          fy[ch] = data[language];
          this.diGui(chs, i, fy, back);
          return;
        }
      } catch(e){
      }

      this.diGui(chs, i, fy, back);
      // this.httpfy(ch, (dst)=>{
      // });
    });
  },

  //替换翻译
  tiHuan(data, fy) {

    if (data == undefined) {
      return data;
    }

    if (data.constructor.name == 'String') {
      try {
        data = JSON.parse(data);
        data = this.tiHuan(data, fy);
        return JSON.stringify(data);
      } catch (e){
        var numRe = new RegExp("[\\u4E00-\\u9FFF]+","g");
        if (numRe.test(data) && fy[data]) {
          return fy[data];
        } else {
          return data;
        }
      }
    }
    
    if (data.constructor.name == 'Array') {
      
      for (let index = 0; index < data.length; index++) {
        var z = data[index];
        data[index] = this.tiHuan(z, fy);
      }
      return data;
    }

    if (data.constructor.name == 'Object') {
      
      for (const key in data) {
        if (nos[key]) continue;
        var z = data[key];
        data[key] = this.tiHuan(z, fy);
      }
      return data;
    }

    return data;
  },
  
  //网络翻译
  httpfy(q, back) {

    var sign = appid + q + salt + key;
    sign = md5(sign);

    var to = languages[language];
    var url = "http://api.fanyi.baidu.com/api/trans/vip/translate?";
    url = url + 'q=' + q; //需要翻译内容 encodeURIComponent(q)
    url = url + '&from=' + 'zh'; //需要翻译内容的语言
    url = url + '&to=' + to; //翻译结果的语言
    url = url + '&appid=' + appid; //APPID
    url = url + '&salt=' + salt; //随机数
    url = url + '&sign=' + sign; //签名
    var options = {'method':'POST',
                   'Content-Type':'application/x-www-form-urlencoded',
                   'url': url, 
                   'type':'json',
                   'body':'HTTP'};
    stream.fetch(options, function(ret) {
      if(ret.ok){
        try{
          
          var data = ret.data.trans_result[0];
          storage.getItem(data.src, (e)=>{

            var dict;
            try{
              dict = JSON.parse(e.data);
            } catch(e){
              dict = {};
            }
            dict[language] = data.dst;
            storage.setItem(data.src, JSON.stringify(dict));
          });
          back(data.dst);
        } catch(e){
          back();
        }
      } else {
        back();
      }
    });
  },
}
